<template>
  <el-button @click='popup("add")'  style="margin: 15px" type="primary" icon="el-icon-plus">添加机器</el-button>
  <el-scrollbar height="calc(100vh - 150px)">
    <div style="margin: 15px">
	  <el-table :data="serverList" style="width: 100%" size="mini" empty-text="暂无数据" border>
    <el-table-column label="序号" align="center" width="60">
      <template #default="scope">
        <span>{{ scope.$index + 1 }}</span>
      </template>
    </el-table-column>
		<el-table-column prop="name" label="服务器名称"  align="center" width="250"></el-table-column>
		<el-table-column prop="host_ip" label="IP"  width="180" align="center"></el-table-column>
		<el-table-column prop="host_port" label="端口" align="center" width="60"></el-table-column>
		<el-table-column prop="creator" label="创建人"  align="center"></el-table-column>
     <el-table-column label="创建时间"  align="center" >
			<template #default="scope">
				{{ $tools.rTime(scope.row.create_time) }}
			</template>
		</el-table-column>
    <el-table-column label="是否设置为默认机器"  align="center" width="150">
			<template #default="scope">
				<el-switch
            @change='switchStatus(scope.row)'
            v-model="scope.row.default_code"
            active-color="#66b1ff" inactive-color="#b1b1b1">

        </el-switch>
			</template>
		</el-table-column>
		<el-table-column label="操作"  align="center">
			<template #default="scope">
					<el-button @click="terminal(scope.row.id)" type="success" size="mini" plain icon="el-icon-view" >进入终端</el-button>
					<el-button @click='popup("edit",scope.row)' type="primary" plain size="mini">编辑</el-button>
					<el-button @click="delServer(scope.row.id)"  size="mini" plain >删除</el-button>
			</template>
		</el-table-column>
	</el-table>
    </div>
    <div class="pagination-container">
      <el-pagination  background layout="total, prev, pager, next, jumper"
                    @current-change="currentPages"
                    :default-page-size="100"
                    :total="pages.count"
                    :current-page="pages.current"
                   next-text="下一页" prev-text="上一页">
      </el-pagination>
    </div>
  </el-scrollbar>
  <!--  弹窗-->
  <el-dialog :title="dialogTitle" v-model="dialogVisible"  :before-close="closeDialog" top="40px" destroy-on-close custom-class="class_dialog">
        <div class="system-icon-content">
          <el-form :model="serverData" :rules="rulesServer" ref="ServerRef" label-position="top">
            <el-form-item label="名称" prop="name">
                <el-input v-model="serverData.name" placeholder="请输入名称"></el-input>
            </el-form-item>
            <el-form-item label="服务器IP" prop="host_ip">
                <el-input v-model="serverData.host_ip" maxlength="15" placeholder="请输入服务器IP"></el-input>
            </el-form-item>
            <el-form-item label="端口号" prop="host_port">
                <el-input v-model="serverData.host_port" maxlength="15" placeholder="请输入端口号"></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="sys_user_name">
                <el-input v-model="serverData.sys_user_name" maxlength="200" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="sys_user_passwd">
                <el-input v-model="serverData.sys_user_passwd" maxlength="200" placeholder="请输入密码"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer" style="text-align: center;">
              <el-button @click="closeDialog" >取 消</el-button>
              <el-button v-if="dialogTitle === '添加机器'" type="primary" @click="clickAdd" >保 存</el-button>
              <el-button v-if="dialogTitle === '编辑机器'" type="primary" @click="clickUpdate" >保 存</el-button>
          </div>
        </div>
  </el-dialog>

</template>

<script>
import {mapMutations, mapState} from "vuex";
export default {
  computed: {
    ...mapState({
      server: state => state.server,
      pro: state => state.pro
    }),
    username() {
			return window.sessionStorage.getItem('username');
		},
  },
  data() {
    return {
        dialogVisible:false,
        dialogType: '', // 对话框类型，用于区分不同类型的对话框
        dialogTitle: '', // 对话框标题，根据不同类型动态设置
        serverList: [],
        serverData: {
          name: '',
          host_ip: '',
          host_port: '',
          sys_user_name: '',
          sys_user_passwd: '',
          creator: '',
          project: '',
        },
        pages: {
          count: 0,
          current: 1
        },
        rulesServer: {
          name: [
            { required: true, message: '请输入机器名称', trigger: 'blur' },
          ],
          host_ip: [
            { required: true, message: '请输入服务器IP', trigger: 'blur' },
          ],
          host_port: [
            { required: true, message: '请输入端口号', trigger: 'blur' },
          ],
          sys_user_name: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
          ],
          sys_user_passwd: [
            { required: true, message: '请输入密码', trigger: 'blur' },
          ],
        },


    }
  },
  methods: {
    ...mapMutations(['servers']),

    terminal(id){
      this.$router.push({name: 'terminal'});
      this.servers(id)
    },

    currentPages(currentPage) {
      this.getServerList(this.pro.id,currentPage)
      this.pages.current = currentPage

  },

    async getServerList() {
     const response =await this.$api.getServers(this.pro.id,1)
     if (response.status ===200){
				this.serverList = response.data.result;
				this.pages = response.data

			}
    },

    async switchStatus(data) {
    let params = {default_code:data.default_code}
    const response =await this.$api.updateServer(data.id,params)
    if (response.status ===200){
				this.$message({
					type: 'success',
					message: '设置成功'
				});
			}
    this.getServerList()

  },

    delServer(id) {
    this.$confirm('此操作将永久删除该机器, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        const response = await this.$api.delServer(id)
        if(response.status ===204){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 刷新页面
          this.getServerList(this.pro.id,1);
        }
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
  },

    async clickUpdate() {
      this.$refs.ServerRef.validate(async vaild => {
      // 判断是否验证通过，不通过则直接retrue
      if (!vaild) return;
      const params = {...this.serverData}
      const response = await this.$api.updateServer(this.serverData.id,params);
      if (response.status === 200) {
        this.$message({
          type: 'success',
          message: '修改成功',
          duration: 1000
       });
       this.dialogVisible= false;
       this.getServerList(this.pro.id,1);
      }
      })
    },

    async clickAdd() {
      this.$refs.ServerRef.validate(async vaild => {
      // 判断是否验证通过，不通过则直接retrue
      if (!vaild) return;
      const params = {...this.serverData}
      const response = await this.$api.createServer(params);
      if (response.status === 201) {
        this.$message({
          type: 'success',
          message: '添加成功',
          duration: 1000
        });
        this.dialogVisible= false;
        this.getServerList(this.pro.id,1);
      }
      })
    },

    popup(type,data) {
      this.dialogType = type;
      this.dialogVisible = true;

      // 根据不同的对话框类型设置标题
      switch (type) {
        case 'add':
          this.dialogTitle = '添加机器';
          this.serverData.creator = this.username;
          this.serverData.project = this.pro.id;
          break;

        case 'edit':
          this.dialogTitle = '编辑机器';
          this.serverData = data;
          break;

        default:
          this.dialogTitle = '';
          break;
      }
    },

    closeDialog() {
      this.dialogVisible = false;
      this.getServerList(this.pro.id,1);
      this.serverData = '';
    },


  },


created() {
    this.getServerList()
  }
}
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>